/**
 * @description ： 用户模块
 */
const userModel = require("../models/userModel")
const qs = require("qs")
const moment = require("moment")

/**
 * 用户注册
 * 
 * @param {Express.Request} req 
 * @param {Express.Response} res 
 */
const register = async (req, res) => {
    var reqBody = req.body ? qs.parse(req.body) : {}
    if (!reqBody.acccount) {
        return res.sendFailure("非法参数", 2);
    }
    try {
        let findRet = await userModel.aggregate([{ $match: { account: account, status: 1 } }, { $count: "count" }])
        if (findRet[0]?.account > 0) {
            return res.sendFailure("账号已存在");
        }
    } catch (err) {
        return res.sendFailure("查询时出现错误")
    }

    try {
        const { account, password, nickname, create_user } = reqBody;
        let insertArr = {
            account, password, nickname, create_user,
            create_time: moment().format("YYYY-MM-DD HH:mm:ss")
        }
        let createRet = await userModel.create(insertArr);
        res.sendSuccess();
    } catch (err) {
        return res.sendFailure("账号注册失败")
    }
}

/**
 * 用户登录
 * 
 * @param {Express.Request} req 
 * @param {Express.Response} res 
 */
const login = async (req, res) => {
    var reqBody = req.body ? qs.parse(req.body) : {}
    if (!reqBody.acccount) {
        return res.sendFailure("非法参数", 2);
    }
    try {
        let findRet = await userModel.aggregate([{ $match: { account: account, status: 1 } }, { $count: "count" }])
        let data = findRet[0]
        if (data?.account <= 0) {
            return res.sendFailure("账号或密码错误");
        }
        if (data.password != reqBody.password) {
            return res.sendFailure("账号或密码错误");
        }
        res.sendSuccess()
    } catch (err) {
        return res.sendFailure("查询操作有误")
    }

}